package org.openscheduler.common.web.listener;

import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.openscheduler.common.exception.SchedulerRuntimeException;
import org.openscheduler.modules.scheduler.SchedulerRepository;
import org.openscheduler.modules.scheduler.SchedulerService;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SchedulerInitializerListener implements ServletContextListener, HttpSessionListener {

	protected Logger logger = LoggerFactory.getLogger(SchedulerInitializerListener.class);
	
	private boolean waitForJobsToComplete;
	
//	@Autowired
//	SchedulerService schedulerService;
//	
//	@Autowired
//	SchedulerRepository schedulerRepository;
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
//		WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);
//		
//		WebApplicationContext wc = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
//		wc.getBean("schedulerRepository");
//		wc.getBean("schedulerService");
//		
//		logger.info("Context Initialized");
//		waitForJobsToComplete = true;
//		for (String id : schedulerRepository.getAllIds()) {
//			try {
//				new StdSchedulerFactory(schedulerRepository.get(id)).getScheduler();
//			} catch (SchedulerException e) {
//				throw new SchedulerRuntimeException(e);
//			}
//		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
//		logger.info("Context Destroyed");
//		try {
//			for (Scheduler scheduler : schedulerService.getAllSchedulers()) {
//				if (!scheduler.getMetaData().isSchedulerRemote()) {
//					scheduler.shutdown(waitForJobsToComplete);
//				}
//			}
//		} catch (SchedulerException e) {
//			e.printStackTrace();
//		}
	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		// TODO Auto-generated method stub
		
	}

}
